var wfCommonConfig = new Object(); //全局配置
wfCommonConfig.doc = new Object();
wfCommonConfig.doc.fileVipButton = "送10个月VIP";

//接口请求地址
function wfgetAPI(serviceName){
    let ApiHost = '';
    let host = document.domain;
    let hostArr = host.split(".");
    if(!serviceName){
      serviceName = hostArr[0];
    }
    let protocol = window.location.protocol;
    if(hostArr[1] == 'test'){
      if(serviceName!='live'){
        protocol = 'http:'
      }
      ApiHost =  protocol+'//'+serviceName+'.test.mbalib.com';
    }else if(hostArr[1] == 'test2'){
      if(serviceName!='live'){
        protocol = 'http:'
      }
      ApiHost =  protocol+'//'+serviceName+'.test2.mbalib.com';
    }else if(hostArr[1] == 'dev'){
      if(serviceName!='live'){
        protocol = 'http:'
      }
      ApiHost =  protocol+'//'+serviceName+'.dev.mbalib.com';
    }else{
      ApiHost =  protocol+'//'+serviceName+'.mbalib.com';
    }
    return ApiHost;
}
  
//获得服务器地址
function wfgetServer(serviceName){
    let ApiHost = '';
    let host = document.domain;
    let hostArr = host.split(".");
    if(!serviceName){
      serviceName = hostArr[0];
    }
    let protocol = window.location.protocol;
    if(hostArr[1] == 'test'){
      if(serviceName!='live'){
        protocol = 'http:'
      }
      if(serviceName == 'static' || serviceName == 'img'){
        ApiHost = protocol+'//static.test.mbalib.com';
      }else{
        ApiHost =  protocol+'//'+serviceName+'.test.mbalib.com';
      }
    }else if(hostArr[1] == 'test2'){
      if(serviceName!='live'){
        protocol = 'http:'
      }
      if(serviceName == 'static' || serviceName == 'img'){
        ApiHost = protocol+'//static.test2.mbalib.com';
      }else{
        ApiHost =  protocol+'//'+serviceName+'.test2.mbalib.com';
      }
    }else if(hostArr[1] == 'dev'){
      if(serviceName!='live'){
        protocol = 'http:'
      }
      if(serviceName == 'static' || serviceName == 'img'){
        ApiHost = protocol+'//img.dev.mbalib.com';
      }else{
        ApiHost =  protocol+'//'+serviceName+'.dev.mbalib.com';
      }
    }else{
      if(serviceName == 'static' || serviceName == 'img'){//微信分享要包括window.location.protocol
        ApiHost =  window.location.protocol + '//img.mbalib.com';
      }else{
        ApiHost =  window.location.protocol + '//'+serviceName+'.mbalib.com';
      }
    }
    return ApiHost;
}

function replaceUrlParam(url, arg, argVal) {
    var pattern = new RegExp('([\?|\&])(' + arg + '=)([^&]+)', 'ig');
    var replaceText = arg + '=' + argVal;
    return url.match(pattern) ? url.replace(pattern, '$1' + replaceText) : (url.match('[?]') ? url + '&' + replaceText : url + '?' + replaceText);
}

function wfVerifyMobile(mobile) {
    var telReg = !!mobile.match(/^\+?(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$/);
    return telReg;
}

function wfEnvironmentUrl(channel) {
    var cServer;
    var environment;
    var domain = document.domain;
    if (domain.indexOf(".dev") != -1 || domain.indexOf(".test2") != -1) {
        environment = 'dev';
    } else if (domain.indexOf(".test") != -1) {
        environment = 'test';
    }

    if (environment) {
        cServer = "http://" + channel + "." + environment + ".mbalib.com";
    } else {
        cServer = "https://" + channel + ".mbalib.com";
    }
    return cServer;
}

function wfIsPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
        "SymbianOS", "Windows Phone",
        "iPad", "iPod"
    ];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

function wfViewLog(type, key) {
    return false;
    var server = wfEnvironmentUrl("www");
    var logUrl = server + "/log/appviewlog";
    var token = wfGetCookie("wikidbAccessToken");
    if (!token) return;
    $.post(logUrl, { type: type, key: key, access_token: token }, function(result) {
        console.log(result);
    }, 'json')
}

function wfIsApp() {
    var u = navigator.userAgent;
    if (u.indexOf("MBALIB-") != -1) {
        return true;
    }
    return false;
}

//是否在微信环境下
function isWeixinClient() {
    if (navigator.userAgent.toLowerCase().indexOf("micromessenger") > 0) {
      return true;
    }
    return false;
}

function wfIsIosApp() {
    var u = navigator.userAgent;
    if (u.indexOf("MBALIB") != -1) {
        var isiOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1 || u.indexOf('iPod') > -1 || u.indexOf('iOS') > -1; //Android终端
        return isiOS;
    }
    return false;
}

function wfIsAnroidApp() {
    var u = navigator.userAgent;
    if (u.indexOf("MBALIB") != -1) {
        var flag = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //Android终端
        return flag;
    }
    return false;
}

function wfGetUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象

    var r = window.location.search.substr(1).match(reg); //匹配目标参数

    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}




function getAgent(sort) {
    var agent = navigator.userAgent;
    var pattern;
    if (agent.indexOf("MBALIB") != -1) {
        if (sort == 'client') {
            pattern = /MBALIB.*?(Android|iPhone)/;
        } else if (sort == 'equipment') {
            pattern = /MBALIB.*?(iPad|iPhone)/;
        } else if (sort == 'version') {
            pattern = /APP\/([\d\.]*)/; //MBALIB-WIKI-APP/6.6.8(iPad7,5;iOS 12.3.1;mbalibnormal;zh-cn;Build/370)
        } else if (sort == 'build') {
            pattern = /Build\/(\d+)/;
        } else if (sort == 'channel') {
            pattern = /MBALIB-(.*?)-/;
        } else if (sort == 'device') {
            pattern = /Device\/(.*?)(?=;)/i;
        }
        var result = agent.match(pattern); //返回包含所有匹配的数组
        return result;

    }
    return null;
}

function isOldAppVerion(newVersion) {
    var version = getAgent('version');
    if (version) {
        version = version[0].substr(4);
        if (version < newVersion) {
            return true;
        } else {
            return false;
        }
    }
}


function addCssByLink(url) {
    var doc = document;
    var link = doc.createElement("link");
    link.setAttribute("rel", "stylesheet");
    link.setAttribute("type", "text/css");
    link.setAttribute("href", url);

    var heads = doc.getElementsByTagName("head");
    if (heads.length)
        heads[0].appendChild(link);
    else
        doc.documentElement.appendChild(link);
}

function addCssByScript(url) {
    var doc = document;
    var script = doc.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("href", url);

    var heads = doc.getElementsByTagName("head");
    if (heads.length)
        heads[0].appendChild(script);
    else
        doc.documentElement.appendChild(script);
}

function wfGetCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

function wfSetCookie(c_name, value, minute, domain) {
    var exdate = new Date();
    //exdate.setDate(exdate.getDate()+expiredays);
    exdate.setTime(exdate.getTime() + 60 * 1000 * minute);
    document.cookie = c_name + "=" + escape(value) + ";path=/;domain=" + domain +
        ((minute == null) ? "" : ";expires=" + exdate.toGMTString());
}

function wfSetCookieNo(c_name, value, minute, domain) {
    var exdate = new Date();
    //exdate.setDate(exdate.getDate()+expiredays);
    exdate.setTime(exdate.getTime() + 60 * 1000 * minute);
    document.cookie = c_name + "=" + (value) + ";path=/;domain=" + domain +
        ((minute == null) ? "" : ";expires=" + exdate.toGMTString());
}

function wfDeleteCookie(name, domain) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    console.log(exp.toGMTString());
    var cval = wfGetCookie(name);
    console.log(cval);
    if (cval != null)
        document.cookie = name + "=" + cval + ";path=/;domain=" + domain + ";expires=" + exp.toGMTString();
}

function wfGetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}



//判断网络状态
function netWordState() {
    if (navigator.onLine != 'undefined') {
        return navigator.onLine;
    }
    return true;
    // 是否在线
    //navigator.onLine

    // 连接类型 兼容性不好
    //navigator.connection.type
    //type: unknown, ethernet, wifi, 2g, 3g, 4g, none.

    // 下行最大比特率 兼容性不好 
    //navigator.connection.downlinkMax

}

/**
 * 时间戳格式化函数
 * @param  {string} format    格式
 * @param  {int}    timestamp 要格式化的时间 默认为当前时间
 * @return {string}           格式化的时间字符串
 */
function wfDate(format, timestamp) {
    var a, jsdate = ((timestamp) ? new Date(timestamp * 1000) : new Date());
    var pad = function(n, c) {
        if ((n = n + "").length < c) {
            return new Array(++c - n.length).join("0") + n;
        } else {
            return n;
        }
    };
    var txt_weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    // var txt_weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    var txt_ordin = { 1: "st", 2: "nd", 3: "rd", 21: "st", 22: "nd", 23: "rd", 31: "st" };
    var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    // var txt_months = [" ", "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
    var f = {
        // Day
        d: function() { return pad(f.j(), 2) },
        D: function() { return f.l().substr(0, 3) },
        j: function() { return jsdate.getDate() },
        l: function() { return txt_weekdays[f.w()] },
        N: function() { return f.w() + 1 },
        S: function() { return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th' },
        w: function() { return jsdate.getDay() },
        z: function() { return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0 },

        // Week
        W: function() {
            var a = f.z(),
                b = 364 + f.L() - a;
            var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
            if (b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b) {
                return 1;
            } else {
                if (a <= 2 && nd >= 4 && a >= (6 - nd)) {
                    nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                    return date("W", Math.round(nd2.getTime() / 1000));
                } else {
                    return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                }
            }
        },

        // Month
        F: function() { return txt_months[f.n()] },
        m: function() { return pad(f.n(), 2) },
        M: function() { return f.F().substr(0, 3) },
        n: function() { return jsdate.getMonth() + 1 },
        t: function() {
            var n;
            if ((n = jsdate.getMonth() + 1) == 2) {
                return 28 + f.L();
            } else {
                if (n & 1 && n < 8 || !(n & 1) && n > 7) {
                    return 31;
                } else {
                    return 30;
                }
            }
        },

        // Year
        L: function() { var y = f.Y(); return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0 },
        //o not supported yet
        Y: function() { return jsdate.getFullYear() },
        y: function() { return (jsdate.getFullYear() + "").slice(2) },

        // Time
        a: function() { return jsdate.getHours() > 11 ? "pm" : "am" },
        A: function() { return f.a().toUpperCase() },
        B: function() {
            // peter paul koch:
            var off = (jsdate.getTimezoneOffset() + 60) * 60;
            var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off;
            var beat = Math.floor(theSeconds / 86.4);
            if (beat > 1000) beat -= 1000;
            if (beat < 0) beat += 1000;
            if ((String(beat)).length == 1) beat = "00" + beat;
            if ((String(beat)).length == 2) beat = "0" + beat;
            return beat;
        },
        g: function() { return jsdate.getHours() % 12 || 12 },
        G: function() { return jsdate.getHours() },
        h: function() { return pad(f.g(), 2) },
        H: function() { return pad(jsdate.getHours(), 2) },
        i: function() { return pad(jsdate.getMinutes(), 2) },
        s: function() { return pad(jsdate.getSeconds(), 2) },
        //u not supported yet

        // Timezone
        //e not supported yet
        //I not supported yet
        O: function() {
            var t = pad(Math.abs(jsdate.getTimezoneOffset() / 60 * 100), 4);
            if (jsdate.getTimezoneOffset() > 0) t = "-" + t;
            else t = "+" + t;
            return t;
        },
        P: function() { var O = f.O(); return (O.substr(0, 3) + ":" + O.substr(3, 2)) },
        //T not supported yet
        //Z not supported yet

        // Full Date/Time
        c: function() { return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P() },
        //r not supported yet
        U: function() { return Math.round(jsdate.getTime() / 1000) }
    };

    return format.replace(/[\\]?([a-zA-Z])/g, function(t, s) {
        if (t != s) {
            // escaped
            ret = s;
        } else if (f[s]) {
            // a date function exists
            ret = f[s]();
        } else {
            // nothing special
            ret = s;
        }
        return ret;
    });
}

// --------- 首页 ----------

// 首页频道入口
function statHomeChannelEntrance(channel) {
    console.log(channel);
    _hmt.push(['_trackEvent', 'home_channel_entrance', channel]);
}

function statTopChannelEntrance(channel) {
    _hmt.push(['_trackEvent', 'top_channel_entrance', channel]);
}


// --------- 课堂 ----------

//课堂音频加载时间
function statKetangLoadAudioTime(type, time) {
    _hmt.push(['_trackEvent', 'ketang_audio', 'load', type, time]);
}

//课堂VIP专题页 调整课堂首页按钮点击事件
function statKetangVipGoHome() {
    _hmt.push(['_trackEvent', 'ketang_vip_go_home_click', 'ketang_vip_go_home_click']);
}

//

//大咖讲百科分享页音频加载时间
function statWikiLoadAudioTime(time) {
    _hmt.push(['_trackEvent', 'wiki_audio', 'load', 'audio', time]);
}

//大咖讲百科 7天活动
//分享数
function statWikiActivityShare() {
    _hmt.push(['_trackEvent', 'wiki_audio_activity_share', 'wiki_audio_activity_share']);
}

function statWikiActivityGet() {
    _hmt.push(['_trackEvent', 'wiki_audio_activity_get', 'wiki_audio_activity_get']);
}

function statWikiActivityShareButton() {
    _hmt.push(['_trackEvent', 'wiki_audio_activity_share_button', 'wiki_audio_activity_share_button']);
}

function statWikiActivityEntry() {
    _hmt.push(['_trackEvent', 'wiki_audio_activity_entry', 'wiki_audio_activity_entry']);
}

//相关课程点击侧边
function statRelateCourseRight(channel) {
    _hmt.push(['_trackEvent', 'relate_course_right_click', channel]);
}

//相关课程点击底部
function statRelateCourseBottom(channel) {
    _hmt.push(['_trackEvent', 'relate_course_bottom_click', channel]);
}

//百科分享点击
function statWikiShare(title) {
    _hmt.push(['_trackEvent', 'wiki_click_share', title]);
}

//百科打赏按钮点击
function statWikiReward(title) {
    _hmt.push(['_trackEvent', 'wiki_click_reward', title]);
}

//百科下载按钮点击
function statWikiDownloadApp(type) {
    _hmt.push(['_trackEvent', 'wiki_click_download_app', type]);
}

//百科查看全文点击
function statWikiShowAllPage() {
    _hmt.push(['_trackEvent', 'wiki_click_show_all', 'page']);
}

//百科左侧悬浮广告点击
function statWikiClickLeftAd() {
    _hmt.push(['_trackEvent', 'wiki_click_left_ad', 'click_left_ad']);
}

//百科浏览到条目底部方法
//type - wiki_view_finish_pc,wiki_view_finish_mobile,wiki_view_finish_app
function statWikiViewFinish(type) {
    _hmt.push(['_trackEvent', 'wiki_view_finish', type]);
}

//百科选中文字统计
function statWikiSelection() {
    _hmt.push(['_trackEvent', 'wiki_selection', 'selection']);
}

//百科顶部搜索栏点击统计
function statwikiSearchClick() {
    _hmt.push(['_trackEvent', 'wiki_selection', 'search_click']);
}

//百科顶部搜索栏回车搜索点击统计
function statwikiSearchEnter() {
    _hmt.push(['_trackEvent', 'wiki_selection', 'wiki_search_enter']);
}

//百科顶部搜索按钮点击统计
function statwikiSearchBtn() {
    console.log('wiki_search_btn');
    _hmt.push(['_trackEvent', 'wiki_selection', 'wiki_search_ResultList']);
}

//百科复制统计
function statWikiCopy() {
    if (wfIsPC()) {
        var s = 'wiki_copy_pc';
    } else {
        var s = 'wiki_copy_mobile';
    }
    _hmt.push(['_trackEvent', 'wiki_copy', s]);
}

function statWikiCopyPopKnowClick() {
    _hmt.push(['_trackEvent', 'wiki_copy_pop_know_click', 'wiki_copy_pop_know_click']);
}

function statWikiCopyPopNoshowClick() {
    _hmt.push(['_trackEvent', 'wiki_copy_pop_noshow_click', 'wiki_copy_pop_noshow_click']);
}

//百科复制弹层 弹出
function statWikiCopyPop() {
    _hmt.push(['_trackEvent', 'wiki_copy', 'wiki_copy_pop']);
}

//百科app扫码成功获取复制权限
function statWikiCopyPopScan() {
    _hmt.push(['_trackEvent', 'wiki_copy', 'wiki_copy_scan']);
}

//百科VIP弹窗打开
function statWikiPcVipPop() {
    _hmt.push(['_trackEvent', 'wiki_vip', 'wiki_pc_vip_pop']);
}

//百科VIP阅读完成弹窗打开
function statReadEndVipPop() {
    _hmt.push(['_trackEvent', 'wiki_vip', 'read_end_vip_pop']);
}



//百科收藏点击统计
function statWikiFavorite() {
    _hmt.push(['_trackEvent', 'wiki_favorite', 'favorite']);
}

//百科显示下载APP二维码
function statWikiShowAppQrcode() {
    _hmt.push(['_trackEvent', 'wiki_show_app_qrcode', 'show_app_qrcode']);
}

//展示条目二维码
function stateWikiShowQrcode() {
    _hmt.push(['_trackEvent', 'qrcode', 'qrcode_show']);
}

//二维码进入的访问
function stateWikiVisitQrcode() {
    _hmt.push(['_trackEvent', 'qrcode', 'qrcode_visit']);
}

//大咖分享页访问
function stateWikiAudioVisit() {
    _hmt.push(['_trackEvent', 'wiki_audio_visit', 'audio_visit']);
}

//大咖讲百科VIP页底部按钮
function stateWikiAudioVip(type) {
    _hmt.push(['_trackEvent', 'wiki_audio_button_click', type]);
}

//百科相关文档
//type-wiki_doc_visit_mobile,wiki_doc_visit_pc
function stateWikiDocVisit() {
    type = 'wiki_doc_visit_pc';
    if (!wfIsPC())
        type = 'wiki_doc_visit_mobile';
    _hmt.push(['_trackEvent', 'wiki_doc_visit', type]);
}


//----------文档--------

// pc全局-头部-文档VIP
function statePCAllHeadJionVIP(){
    console.log('PC_All_HeadJionVIP');
    _hmt.push(['_trackEvent', 'All_', 'PC_All_HeadJionVIP']);
}
// pc全局-头部-文档积分
function statePCAllHeadJionWealth(){
    console.log('PC_All_HeadJionWealth');
    _hmt.push(['_trackEvent', 'All_', 'PC_All_HeadJionWealth']);
}

// pc全局-头部-文档VIP菜单-开通文档VIP
function statePCAllHeadJionMenuVIP(){
    console.log('PC_All_HeadJionMenuVIP');
    _hmt.push(['_trackEvent', 'All_', 'PC_All_HeadJionMenuVIP']);
}

//文档详情页-底部操作栏-下载文档-充值
function statePCRechargeDownloadClick() {
    console.log('pc_recharge_download');
    _hmt.push(['_trackEvent', 'recharge_url_click', 'pc_recharge_download']);
}

//文档详情页-顶部操作栏-开通VIP
function statePCMemberViewTopClick() {
    console.log('pc_member_view_top');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_member_view_top']);
}

//文档详情页-顶部操作栏-开通VIP
function statePcMemberRenewViewTopClick() {
    console.log('pc_member_renew_view_top');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_member_renew_view_top']);
}

//文档详情页-底部操作栏-续费VIP
function statePcMemberRenewViewBottomClick() {
    console.log('pc_member_renew_view_bottom');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_member_renew_view_bottom']);
}

//文档详情页-底部操作栏-开通VIP
function statePCMemberViewBottomClick() {
    console.log('pc_member_view_bottom');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_member_view_bottom']);
}

//文档详情页-阅读结束底部-加入VIP
function statePCMemberViewReadBottomClick() {
    console.log('pc_member_view_read_bottom');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_member_view_read_bottom']);
}

//文档下载文档页积分不足时出现加入VIP按钮
function stateMemberDownloadPageClick(type) {
    if(type == 'rmb'){
        console.log('MonneyFilePay_JionVIP_0');
        _hmt.push(['_trackEvent', 'member_url_click', 'MonneyFilePay_JionVIP_0']);
    } else {
        console.log('member_download_page');
        _hmt.push(['_trackEvent', 'member_url_click', 'member_download_page']);
    }
}

//PC_文档下载页_开通VIP入口点击
function statePcDownloadPageVipEntranceChick(){
    console.log('PC_DownloadPage_VipEntrance_Chick');
    _hmt.push(['_trackEvent', 'member_url_click', 'PC_DownloadPage_VipEntrance_Chick']);
}

//PC_文档下载页_前往积分入口点击
function statePCDownloadPageWealthEntranceChick(){
    console.log('PC_DownloadPage_WealthEntrance_Chick');
    _hmt.push(['_trackEvent', 'member_url_click', 'PC_DownloadPage_WealthEntrance_Chick']);
}

//积分购买文档页-非Vip用户去Vip开通页
function stateNonMemberDownloadPageClick(){
    console.log('non_member_download_page');
    _hmt.push(['_trackEvent', 'member_url_click', 'non_member_download_page']);
}

//积分购买文档页-续费VIP
function statePCMemberRenewDownloadClick() {
    console.log('pc_member_renew_download');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_member_renew_download']);
}

//现金文档支付页-续费VIP按钮
function stateMemberRenewDownloadPageClick() {
    console.log('member_renew_download_page');
    _hmt.push(['_trackEvent', 'member_url_click', 'member_renew_download_page']);
}

//专题页-底部的开通按钮
function statePCTopicViewBottomClick() {
    console.log('pc_topic_view_bottom');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_topic_view_bottom']);
}


//专题详情页-底部-续费VIP按钮
function statePCTopicRenewViewBottomClick() {
    console.log('pc_topic_renew_view_bottom');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_topic_renew_view_bottom']);
}

//专题-购买信息页-加入VIP
function stateTopicDownloadPageClick() {
    console.log('topic_download_page');
    _hmt.push(['_trackEvent', 'member_url_click', 'topic_download_page']);
}

//专题-购买信息页-非Vip用户去Vip开通页
function stateNonTopicDownloadPageClick(){
    console.log('non_topic_download_page');
    _hmt.push(['_trackEvent', 'member_url_click', 'non_topic_download_page']);
}

//专题-购买信息页-续费VIP按钮
function stateTopicRenewDownloadPageClick() {
    console.log('topic_renew_download_page');
    _hmt.push(['_trackEvent', 'member_url_click', 'topic_renew_download_page']);
}


//积分专题支付页-立即充值按钮（积分不足时才出现）
function statePcTopicClick() {
    console.log('pc_topic');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_topic']);
}


//个人中心首页-开通会员
function statePcMemberPersonHomeClick() {
    console.log('pc_member_person_home');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_member_person_home']);
}

//个人中心-续费VIP
function statePcMemberRenewPersonHomeClick() {
    console.log('pc_member_renew_person_home');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_member_renew_person_home']);
}

//个人中心首页-马上充值
function statePcRechargePersonHomeClick() {
    console.log('pc_recharge_person_home');
    _hmt.push(['_trackEvent', 'recharge_url_click', 'pc_recharge_person_home']);
}



//信息支付页面的弹窗-开通VIP   全局-页面右上角-加入VIP
function statePCMemberPOPClick() {
    console.log('pc_member_pop');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_member_pop']);
}

//全局-页面右上角-账户充值
function statePCRechargeTopClick() {
    console.log('pc_recharge_top');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_recharge_top']);
}

//文档通用导航-充值积分
function statePCRechargeNavClick() {
    console.log('pc_recharge_nav');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_recharge_nav']);
}

//文档通用导航-加入VIP
function statePCMemberNavClick() {
    console.log('pc_member_nav');
    _hmt.push(['_trackEvent', 'member_url_click', 'pc_member_nav']);
}


//文档手机端详情页继续阅读点击
function stateDocMobileShowAllClick() {
    _hmt.push(['_trackEvent', 'mobile_view', 'mobile_view_show_all_click']);
}

//文档手机端详情页下载APP按钮1（最底部）
function stateDocMobileShowDownloadClick() {
    _hmt.push(['_trackEvent', 'mobile_view', 'mobile_view_show_download_click']);
}

//文档手机端详情页下载APP按钮2
function stateDocMobileShowDownload2Click() {
    _hmt.push(['_trackEvent', 'mobile_view', 'mobile_view_show_download2_click']);
}

//文档手机端下载按钮点击统计
function stateDocMobileDownloadClick() {
    _hmt.push(['_trackEvent', 'mobile_download', 'mobile_download_click']);
}

//文档手机端收藏按钮点击统计
function stateDocMobileFavoriteClick() {
    _hmt.push(['_trackEvent', 'mobile_favorite', 'mobile_favorite_click']);
}

//文档手机端(8折下载)按钮点击统计
function stateDocMobileVipClick() {
    _hmt.push(['_trackEvent', 'mobile_vip_download', 'mobile_vip_download_click']);
}

//文档手机端(开通VIP)按钮点击统计
function stateDocMobileVipUrlClick() {
    _hmt.push(['_trackEvent', 'mobile_vip_download', 'mobile_vip_url_click']);
}

//文档手机端（使用电脑下载）按钮点击统计
function stateDocMobilePcClick() {
    console.log('stateDocMobilePcClick');
    _hmt.push(['_trackEvent', 'mobile_pc_download', 'mobile_pc_download_click']);
}

//文档PC端未登录点击下载统计
function stateDocPcNoLoginDownloadClick() {
    console.log('stateDocPcNoLoginDownloadClick');
    _hmt.push(['_trackEvent', 'pc_no_login_download', 'pc_no_login_download_click']);
}

//文档PC端未登录点击VIP统计
function stateDocPcNoLoginVipClick() {
    console.log('stateDocPcNoLoginVipClick');
    _hmt.push(['_trackEvent', 'pc_no_login_vip', 'pc_no_login_vip_click']);
}

//文档手机端分享按钮点击统计
function stateDocMobileShareClick() {
    _hmt.push(['_trackEvent', 'mobile_share', 'mobile_share_click']);
}

//文档PC端搜索下载数字码统计
function stateDocDownloadCodeClick() {
    _hmt.push(['_trackEvent', 'mobile_download', 'download_code_click']);
}

//文档PC端详情页浏览统计
function stateDocDetailView() {
    _hmt.push(['_trackEvent', 'doc_detail', 'doc_detail_view']);
}

//-------------PASSORT-----------
//登录绑定手机跳过
function stateLoginBindMobileContinue() {
    _hmt.push(['_trackEvent', 'login_bind_mobile', 'login_bind_mobile_continue']);
}

//登录绑定手机成功
function stateLoginBindMobileSuccess() {
    _hmt.push(['_trackEvent', 'login_bind_mobile', 'login_bind_mobile_success']);
}

//登录绑定手机失败
function stateLoginBindMobileFailure() {
    _hmt.push(['_trackEvent', 'login_bind_mobile', 'login_bind_mobile_failure']);
}

function stateLoginScan() {
    _hmt.push(['_trackEvent', 'LoginPage', 'LoginPage_ScanLoginBtn']);
}

function stateLoginDefault() {
    _hmt.push(['_trackEvent', 'LoginPage', 'LoginPage_AccountLoginBtn']);
}

//展示文档详情二维码
function stateDocShowQrcode() {
    _hmt.push(['_trackEvent', 'doc_qrcode', 'doc_qrcode_show']);
}

//二维码进入的访问
function stateDocVisitQrcode() {
    _hmt.push(['_trackEvent', 'doc_qrcode', 'doc_qrcode_visit']);
}


var _start = 0;
var _loadState = 1;
var _loadEmpty = 0;
/**
 * 加载分页
 * @param callback 回调方法
 * @param params 回调方法其他参数
 */
function loadScrollData(callback, params) {
    $(".loading").show();
    callback(_start, params);
    $(window).scroll(function() {
        if ($(document).scrollTop() >= $(document).height() - $(window).height() - 80) {
            if (_loadState == 1 || _loadEmpty == 1) return false;
            _loadState = 1;
            callback(_start, params);
        }
    });
}

/**
 * 设置加载初始值/加载状态
 * @param num
 */
function setLoadStart(num) {
    _start += ~~num;
    _loadState = 0;
    _loadEmpty = num == 0 ? 1 : 0;
    $(".loading").hide();
}

/**
 * js新窗口打开不被浏览器拦截处理
 */
function locationIgnoreBrowser(url) {
    //var tempwindow=window.open();
    //tempwindow.location= url;
    $("#alipay_form [name='url']").val(url);
    $("#alipay_form").submit();
}

function jumpLogin() {
    var l = window.location.href;
    var host = document.domain;
    var hostArr = host.split(".");
    var domain = "//passport.mbalib.com";
    if (hostArr[1] == 'dev') {
        domain = "//passport.dev.mbalib.com";
    } else if (hostArr[1] == 'test') {
        domain = "//passport.test.mbalib.com";
    } else if (hostArr[1] == 'test2') {
        domain = "//passport.test2.mbalib.com";
    }
    location.href = domain + "/login?continue=" + encodeURIComponent(l);
}

//HTML转义
function HTMLEncode(html) {
    var temp = document.createElement("div");
    (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
    var output = temp.innerHTML;
    temp = null;
    return output;
}
//HTML反转义
function HTMLDecode(text) {
    var temp = document.createElement("div");
    temp.innerHTML = text;
    var output = temp.innerText || temp.textContent;
    temp = null;
    return output;
}
/*
 *  公共对话框
 */
var dialogObj = {
    bg: $('<div class="bg"></div>'),
    hasDialog: false, //是否已存在
    success: function() {},
    close: function() {},
    pop: function(obj) {
        var _this = this;
        var title = obj.title ? obj.title : '';
        var msg = obj.msg ? obj.msg : '';

        if ($("#warnBox").length > 0) {
            this.hasDialog = true
        }

        if (_this.hasDialog == false) {
            html = '<div class="adaptionDialog common-Dialog" id="warnBox">' +
                '<a class="closeIcon" href="javascript:void(0)" ><i></i></a>' +
                '<h4 class="title">' + title + '</h4>' +
                '<div class="body">' +
                '<p class="msg" style="font-size: 1.1rem">' + msg + '</p>' +
                '</div>' +
                '<div class="bottom" style="width: auto">' +
                '<a href="javascript:void(0)" style="margin:0 auto;float: none"   class="cbtn-m btnlook1" >确认</a>' +
                '</div></div>';
            $('body').append(html);
            $('body').append(_this.bg);
            _this.hasDialog = true;
            this.bindEvent();
        } else {
            $('#warnBox .title').html(title);
            $('#warnBox .msg').html(msg);
            $('#warnBox').show();
        }
        if (this.bg == '') {
            $('body').append('<div class="bg"></div>');
            this.bg = '.bg';
        } else {
            $(_this.bg).show();
        }

        if (typeof obj.success == 'function') {
            _this.success = obj.success;
        }
        if (typeof obj.close == 'function') {
            _this.close = obj.close;
        }
    },
    bindEvent: function() {
        var _this = this;
        $(document).on('click', "#warnBox .closeIcon", function() {
            $('#warnBox').hide();
            $(_this.bg).hide();
            _this.close();
        });
        $(document).on('click', "#warnBox .btnlook1", function() {
            $('#warnBox').hide();
            $(_this.bg).hide();
            _this.success();
        })
    }
};

/* 左右按钮确认框 */
var confirmObj = {
    title: '',
    text: '',
    primaryBtn: '确认',
    cancelBtn: '取消',
    callback: function() {},
    createDom: function() {
        var html = '<div class="bg hid" id="confirmBg"></div>';
        $("body").append(html);
        html = '<div class="center-pop hid" id="confirmBox">' +
            '  <div class="head">' +
            '      <div class="title"></div>' +
            '      <p class="note"></p>' +
            '  </div>' +
            '  <div class="bottom">' +
            '     <a href="javascript:void(0)" class="no-btn" style="border-right:1px solid #ddd">' + this.cancelBtn + '</a>' +
            '     <a href="javascript:void(0)"  class="yes-btn  font-primary">' + this.primaryBtn + '</a>' +
            '  </div>' +
            '</div>';
        $('body').append(html);
    },
    bindEvent: function() {
        var _this = this;
        $("#confirmBg").click(function() {
            _this.closeBox();
        });
        $(".center-pop .yes-btn").click(function() {
            _this.closeBox();
            _this.callback();
        });
        $(".center-pop .no-btn").click(function() {
            _this.closeBox();
        })
    },
    openBox: function(options) {
        if (options.primaryBtn && options.primaryBtn != "") {
            this.primaryBtn = options.primaryBtn;
        }
        if (options.cancelBtn && options.cancelBtn != "") {
            this.cancelBtn = options.cancelBtn;
        }

        if ($("#confirmBox").length == 0) {
            this.createDom();
            this.bindEvent();
        }

        if (options.title && options.title != "") {
            this.title = options.title;
            $("#confirmBox").find(".title").html(this.title);
            $("#confirmBox").find(".head").addClass("hasTitle");
        } else {
            $("#confirmBox").find(".head").removeClass("hasTitle");
        }

        this.text = options.text;
        this.callback = options.callback;
        $("#confirmBox").find(".note").html(options.text);
        $("#confirmBox").removeClass("hid");
        $("#confirmBg").removeClass("hid");
    },
    closeBox: function() {
        $("#confirmBox").addClass("hid");
        $("#confirmBg").addClass("hid");
    }
};

/* 单个按钮提示框 */
var promptObj = {
    title: '',
    text: '',
    primaryBtn: '确认',
    callback: function() {},
    createDom: function() {
        var html = '<div class="bg hid" id="promptBg"></div>';
        $("body").append(html);

        var titleClass = '';
        if (this.title && this.title != "") {
            titleClass = 'hasTitle';
        }
        html = '<div class="center-pop hid" id="promptBox">' +
            '  <div class="head ' + titleClass + '">' +
            '      <div class="title">' + this.title + '</div>' +
            '      <p class="note"></p>' +
            '  </div>' +
            '  <div class="bottom">' +
            '     <a style="margin:0;width:100%;" href="javascript:void(0)"  class="yes-btn  font-primary">' + this.primaryBtn + '</a>' +
            '  </div>' +
            '</div>';
        $('body').append(html);
    },
    bindEvent: function() {
        var _this = this;
        $("#promptBg").click(function() {
            _this.closeBox();
        });
        $(".center-pop .yes-btn").click(function() {
            _this.closeBox();
            _this.callback();
        });
    },
    openBox: function(options) {
        if (options.primaryBtn && options.primaryBtn != "") {
            this.primaryBtn = options.primaryBtn;
        }
        this.title = options.title ? options.title : '';

        $("#promptBg").unbind();
        $(".center-pop .yes-btn").unbind();
        $("#promptBox").remove();
        $("#promptBg").remove();

        this.createDom();
        this.bindEvent();


        this.text = options.text;
        this.callback = options.callback;
        $("#promptBox").find(".note").html(options.text);
        $("#promptBox").removeClass("hid");
        $("#promptBg").removeClass("hid");
    },
    closeBox: function() {
        $("#promptBg").addClass("hid");
        $("#promptBox").addClass("hid");
    }
}


/*
 记录订单入口函数
*/
function entranceSet(type, item) {
    var entrance = { type: type, item: item };
    // sessionStorage.setItem('order_entrance',JSON.stringify(entrance));
    setCookie2('order_entrance', JSON.stringify(entrance), null, '.mbalib.com');
    return true;
}

function setCookie2(c_name, value, expiredays, domain) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + value + ";path=/" +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ';domain=' + domain;
}

/*获取服务器域名*/
function getServer(server) {
    var host = document.domain;
    var hostArr = host.split(".");
    var domain = "//" + server + ".mbalib.com";
    if (hostArr[1] == 'dev' || hostArr[1] == 'test' || hostArr[1] == 'test2') {
        domain = "//" + server + "." + hostArr[1] + ".mbalib.com";
        if (server == 'img' && (hostArr[1] == 'test2' || hostArr[1] == 'test')) {
            domain = "//static." + hostArr[1] + ".mbalib.com";
        }
    }
    return location.protocol + domain;
}

function getAppVersion() {
    var u = navigator.userAgent;
    var first = u.indexOf("/");
    var last = u.indexOf("(");
    var version = u.substr(first + 1, last - first - 1);
    return version;
}

/**
 * 刷新token
 * @param result
 * @param fn_request 获取新token后，重新请求
 * @param fn_success token信息有效，执行后续函数
 */
function freshUserInfo(result, fn_request, fn_success, fn_request_params) {
    //用户信息无效
    if (result && result.errorno == 10001) {
        //重新发起请求
        $.ajax({
            url: getServer('passport') + '/api2/accesstoken',
            data: { login_token: wfGetCookie('wikidbLoginToken') },
            dataType: 'json',
            async: false,
        }).done(function(result) {
            token = result.access_token;
            if (!token) {
                wfDeleteCookie('wikidbAccessToken','.mbalib.com');
                wfDeleteCookie('wikidbLoginToken','.mbalib.com');
                if (wfIsApp()) {
                    if (window.app && typeof window.app.openApp == 'function') {
                        window.app.openApp(JSON.stringify({ type: 'login' }));
                    }
                } else {
                    window.location.href = getServer('passport') + '/login' + '?continue=' + encodeURIComponent(window.location.href);
                }
                return;
            }
            if (typeof wfSetCookie === 'function') {
                wfSetCookie('wikidbAccessToken', result.access_token, '60', '.mbalib.com'); //更新token
            }
            fn_request(fn_request_params);
        }).fail(function() {});
    } else {
        fn_success(result);
    }
}

function wfWechat() {
    if (navigator.userAgent.toLowerCase().indexOf("micromessenger") > 0) {
        return true;
    }
    return false;
}

var toast = function(text) {
    $toast(text, 'center');
}

var $toast = function(text, position) {
    position = position || 'center';
    var div = '';
    if (position == 'center') {
        div = $('<div class="pop-zan-wrap" style="width: initial;z-index: 10001;font-size:16px;display:block;">' + text + '<span></span></div>');
    } else if (position == 'bottom') {
        div = $('<div class="pop-zan-wrap" style="bottom: 6rem;top: auto;width: initial;z-index: 10001;font-size:16px;display:block;">' + text + '<span></span></div>');
    }
    $('body').append(div);
    var width = div.outerWidth();
    div.css('margin-left', -width / 2);
    setTimeout(function() {
        div.fadeOut("normal", div.remove());
    }, 1200);
}



//kb转mb  mb转gb
function unitConverter(fileSize, length) {
    var size = 0;
    var unit = 'B';
    if (fileSize >= 1024) {
        size = fileSize / 1024;
        unit = 'KB';
    }
    if (size >= 1024) {
        size = size / 1024;
        unit = 'MB';
    }
    if (size >= 1024) {
        size = size / 1024;
        unit = 'GB';
    }
    if (size == 0) {
        return '0B'
    }
    return parseFloat(size).toFixed(length ? length : 1) + unit;
}


function getSelectedContentsPerFrame(win) {
    try {
        if (win.getSelection) {
            var range = win.getSelection().getRangeAt(0);
            var container = win.document.createElement('div');
            container.appendChild(range.cloneContents());
            return container.innerHTML
        } else if (win.document.getSelection) {
            var range = win.getSelection().getRangeAt(0);
            var container = win.document.createElement('div');
            container.appendChild(range.cloneContents());
            return container.innerHTML
        } else if (win.document.selection) {
            return win.document.selection.createRange().htmlText
        }
    } catch (err) {
        return ""
    }
}
var IEVersion = function() {
    var userAgent = navigator.userAgent;
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1;
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE;
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    if (isIE) {
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        if (fIEVersion == 7) {
            return 7
        } else if (fIEVersion == 8) {
            return 8
        } else if (fIEVersion == 9) {
            return 9
        } else if (fIEVersion == 10) {
            return 10
        } else {
            return 6
        }
    } else if (isEdge) {
        return 100
    } else if (isIE11) {
        return 11
    } else {
        return 100
    }
};

/**
 * 对数字进行取整或保留两位小数。
 * @param {number|string} number - 要处理的数字，可以是数字或字符串类型。
 * @returns {number|string} - 返回取整或保留两位小数后的结果，类型与输入参数相同。
 */
function roundNumber(number) {
    const parsedNumber = parseFloat(number);
  
    if (isNaN(parsedNumber)) {
        // 如果无法解析为数字，则返回原始输入
        return number;
    }
  
    if (Math.floor(parsedNumber) === parsedNumber) {
        return Math.round(parsedNumber);
    } else {
        return parseFloat(parsedNumber.toFixed(2));
    }
}

/**
 *
 * @param fmt eg.yyyy-MM-dd
 * @param val eg.new Date()
 * @returns {*} eg.2019-12-20
 */
function format(fmt, val) {
    let o = {
        "M+": val.getMonth() + 1, //月份
        "d+": val.getDate(), //日
        "h+": val.getHours(), //小时
        "m+": val.getMinutes(), //分
        "s+": val.getSeconds(), //秒
        "q+": Math.floor((val.getMonth() + 3) / 3), //季度
        "S": val.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (val.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

/**
 * @param {date:string} eg.2019/12/20 12:12
 * @param {fmt:string} eg.'YYYY-MM-DD hh:mm'
 * @returns {string}  eg.2019-12-20
 */
function wfDateFormate1(date,fmt) {
    if (!date) return;
    if(fmt=='YYYY-MM-DD hh:mm') {
        return date.substring(0, 4) + '-' + date.substring(4, 6) + '-' + date.substring(6, 8) +' '+date.substring(8, 10) + ':' + date.substring(10, 12);
    // }else if(fmt=='YYYY-MM-DD hh:mm') {
    }else{
        return date.substring(0, 4) + '-' + date.substring(4, 6) + '-' + date.substring(6, 8);
    }
};

// 站内push 每五分钟请求一次，暂时关闭站内push
(function() {

    // 移动端不请求站内push
    if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
        return;
    }

    // 有些h5页面是PHP写的，站内push会进入
    var locationUrl = window.location.href;
    var urlArr = locationUrl.split('?');
    var c_url = urlArr[0]; //?之前的地址
    var parrent = /passport\.(dev3\.|test\.|dev\.)?mbalib\.com\/(register|login)/;
    if (parrent.test(c_url)) return; // 阻止个别页面发站内push

    var token = wfGetCookie("wikidbAccessToken");
    var login_token = wfGetCookie('wikidbLoginToken');

    var pushTimer = null;
    if (pushTimer) clearInterval(pushTimer);

    if (!window.jQuery) addCssByScript(getServer("img") + "/common/jquery/jquery.js", "js"); // 没有jquery时引入jquery
    addCssByLink(getServer('img') + "/common/push/push.css");

    function getInPushList() {
        token = wfGetCookie("wikidbAccessToken");
        if (!token) return;

        var qsData = {
            access_token: token,
        };

        $.post(
            getServer('www') + "/messageapi/getInPushList",
            qsData,
            function(res) {
                // res.errorno = 10001;
                freshUserInfo(res, getInPushList, getInPushListRes);
            },
            "json"
        );
    }

    function getInPushListRes(res) {
        if (res.list && res.list.length > 0) {
            if (!$('.pushBox').length) $("body").append('<div class="pushBox"></div>');

            toastrHtml(res.list, res.list[0], 0); // 进行循环渲染

            $(".pushBox").on("click", ".push-btn", function(e) {
                e.stopPropagation();
                $(this).closest(".push-con")
                    .animate({ right: "-100%", opacity: 0 }, 350, function() {
                        $(this).remove();
                        let panNum = $(".pushBox").find(".push-con").length;
                        if(panNum >= 3 || res.list.length <= indexFinal + 1) return false;
                        toastrHtml(res.list, res.list[indexFinal + 1], indexFinal + 1);
                    });
            });

            $(".pushBox").on("click", ".push-con", function() {
                // if($(this).attr('data-type') == 'top_voucher') return false;
                getOpeninpush($(this).attr('data-url'), $(this).attr('data-id'));
                $(this).animate({ right: "-100%", opacity: 0 }, 350, function() {
                                $(this).remove();
                                let panNum = $(".pushBox").find(".push-con").length;
                                if(panNum >= 3 || res.list.length <= indexFinal + 1) return false;
                                toastrHtml(res.list, res.list[indexFinal + 1], indexFinal + 1);
                            });
            });

            // $(".pushBox").on("click", ".voucher-btn", function() {
            //     getOpeninpush($(this).attr('data-url'), $(this).attr('data-id'));
            //     $(this).closest(".push-con")
            //         .animate({ right: "-100%", opacity: 0 }, 350, function() {
            //             $(this).remove();
            //             let panNum = $(".pushBox").find(".push-con").length;
            //             if(panNum >= 3 || res.list.length <= indexFinal + 1) return false;
            //             toastrHtml(res.list, res.list[indexFinal + 1], indexFinal + 1);
            //         });
            // });
        }
    }

    var indexFinal;

    function toastrHtml(itemList, item, index) {
        let toastrRandom = new Date().getTime() + Math.random().toString(36).substr(2);;
        let str = '<div class="push-con ' + toastrRandom + ' cursor" data-url="' + item.message_url + '" data-id="' + item.log_id + '" data-type="' + item.style + '">';
        str +=
            '<img class="push-btn" src="' +
            getServer('static') +
            '/common/images/ic_close_filled.png">';

        if (item.img && item.style != 'top_voucher') {
            str += '<img class="push-img" src="' + item.img + '" />';
        }
        str +=
            '<div class="push-tit ' + (item.style == 'top_voucher' ? 'voucher-box' : '') + '"><p>' +
            item.title +
            "</p>";
        if(item.style == 'top_voucher'){
            str += '<div class="voucher">' +
                        '<p>' + item.content + '</p>' +
                        '<div class="voucher-btn">去领取</div>' +
                    '</div>'
        } else {
            str += '<p>' +
            item.content +
            '</p>'
        }

        str += "</div></div>";

        $(".pushBox").append(str);
        indexFinal = index;
        // 在动画完成后接着渲染下一个
        $(".pushBox").find("." + toastrRandom + "").animate({ right: 0, opacity: 1 }, 500, function() {
            // 判断是否还有没渲染，接着渲染
            let panNum = $(".pushBox").find(".push-con").length;
            if (itemList.length <= index + 1 || panNum >= 3) return;
            toastrHtml(itemList, itemList[index + 1], index + 1);

        });
        // setTimeout(function() {
        //     $(".pushBox").find("." + toastrRandom + "").removeClass('')
        //         .animate({ right: "-100%", opacity: 0 }, 350, function() {
        //             $(this).remove();
        //             let panNum = $(".pushBox").find(".push-con").length;
        //             if (itemList.length <= indexFinal + 1 || panNum >= 3) return;
        //             toastrHtml(itemList, itemList[indexFinal + 1], indexFinal + 1);
        //         });
        // }, 10000);
    }

    function getOpeninpush(url, id) {
        let qsData = {
            log_id: id,
            access_token: token,
        }
        $.get(getServer('www') + '/messageapi/openinpush', qsData);

        if (url) {
            if (url.search(/http/) == -1) return
            window.open(url);
        }
    }

    if (token && token != 'undefined' && login_token) {
        setTimeout(function() {
            getInPushList();
        }, 1500);

        pushTimer = setInterval(function() {

            var hiddenProperty = 'hidden' in document ? 'hidden' :
                'webkitHidden' in document ? 'webkitHidden' :
                'mozHidden' in document ? 'mozHidden' :
                null;

            if (!document[hiddenProperty]) {
                getInPushList();
            }

        }, 300000);
    }


    var from_source = wfGetUrlParam('from_source');
    if(from_source){
        wfSetCookie('from_source', from_source,'60', '.mbalib.com');
    }

})();



